//加载字典
function convertOfflineType(value, options, row){
    //sex为自定义字典项
	var statusObj = vm.offline_type;
    for( var i=0;i< statusObj.length;i++ ){
        if(statusObj[i].value == value){
            return '<span>'+statusObj[i].text+'</span>' ;
        }
    }
}
$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'offlinestudy/subscribedate/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true,hidden:true },
            { label: '学习类型', name: 'studytype', index: 'studytype', width: 60 ,formatter:convertOfflineType},
			{ label: '学习时段', name: 'subscribedate', index: 'subscribedate', width: 80 },
			{ label: '开始时间', name: 'startdate', index: 'startdate', width: 80,hidden:true },
			{ label: '结束时间', name: 'enddate', index: 'enddate', width: 80,hidden:true },
			{ label: '预约主键', name: 'typeid', index: 'typeid', width: 80,hidden:true },
			{ label: '人数', name: 'rs', index: 'rs', width: 40 },
			{ label: '学习地点组织机构代码', name: 'address', index: 'address', width: 80,hidden:true },
			{ label: '学习地点', name: 'xxdd', index: 'xxdd', width: 140 },
			{ label: '学习时间', name: 'xxsj', index: 'xxsj', width: 100 }
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
		subscribedate: {},
        ext1: {},
        ext2: {},
        offline_type:[]
	},
    created:function(){
        $.get(baseURL+"sys/dict/select/offline_type",function(r){
            if(r.code == 0) {
                vm.offline_type = r.dict.offline_type;
            }else{
                console.log(r.msg);
            }
        });
    },
    mounted:function(){
        //必须在组件渲染之后调用日期组件
        this.dateDefault();
        this.dateDefind();
    },
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.subscribedate = {};
			vm.ext1={};
			vm.ext2={};
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(id)
		},
		saveOrUpdate: function (event) {
		    if(!vm.checkForm()) return;
            var formdata_array = [];
            formdata_array.push(vm.subscribedate);
            formdata_array.push(vm.ext1);
            formdata_array.push(vm.ext2);
            console.log(formdata_array);
			var url = vm.subscribedate.id == null ? "offlinestudy/subscribedate/save" : "offlinestudy/subscribedate/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(formdata_array),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "offlinestudy/subscribedate/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get(baseURL + "offlinestudy/subscribedate/info/"+id, function(r){
                vm.subscribedate = r.list[0];
                vm.ext1 = r.list[1];
                vm.ext2 = r.list[2];

                $("#datepicker_start").val(vm.subscribedate.startdate);
                $("#datepicker_end").val(vm.subscribedate.enddate);
                $("#datepicker_start_ext1").val(vm.ext1.startdate);
                $("#datepicker_end_ext1").val(vm.ext1.enddate);
                $("#datepicker_start_ext2").val(vm.ext2.startdate);
                $("#datepicker_end_ext2").val(vm.ext2.enddate);

                var xxsj = r.list[0].xxsj;
                var regex = /上午(\d{2}:\d{2})至(\d{2}:\d{2}),下午(\d{2}:\d{2})至(\d{2}:\d{2})/;
                var regex_array = regex.exec(xxsj);
                if(regex.test(xxsj)){
                    $("#datetimepicker1").val(regex_array[1]);
                    $("#datetimepicker2").val(regex_array[2]);
                    $("#datetimepicker3").val(regex_array[3]);
                    $("#datetimepicker4").val(regex_array[4]);
                }

            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page
            }).trigger("reloadGrid");
		},
        dateDefault: function(){
            //初始化日期范围组件
            $('#datepicker_range input,#datepicker_range_ext1 input,#datepicker_range_ext2 input').datepicker({
                language: 'zh-CN',//显示中文
                startView: 0, //选择器开始界面 0：天（默认 1：月2：年3：十年 4：世纪
                minViewMode: 0,//最小选择精度 0：天（最小默认）
                maxViewMode: 2, //最大选择精度 4：世纪（最大默认）
                format: 'yyyy-mm-dd',//显示格式
                minView: "day",//设置只显示到月份
                // initialDate: new Date(),
                autoclose: true,//选中自动关闭
                // todayBtn: true//显示今日按钮
                clearBtn: true //清除按钮
                //todayHighlight: true //今日高亮
            });
        },
        dateDefind: function(){
            $('#datetimepicker1,#datetimepicker2,#datetimepicker3,#datetimepicker4').datetimepicker({
                datepicker:false,
                format:'H:i',
                step:5
            });
        },
        handleInput: function(e){
            if(e.srcElement.name == "subscribedate_rs") {
                vm.subscribedate = Object.assign({}, vm.subscribedate, {
                    rs: e.target.value.replace(/[^\d]/g, '')
                })
            }
            if(e.srcElement.name == "ext1_rs") {
                vm.ext1 = Object.assign({}, vm.ext1, {
                    rs: e.target.value.replace(/[^\d]/g, '')
                })
            }
            if(e.srcElement.name == "ext2_rs"){
                vm.ext2 = Object.assign({}, vm.ext2, {
                    rs: e.target.value.replace(/[^\d]/g, '')
                })
            }

        },
        checkForm :function(){
            var result = true;
            $.each($(".form-horizontal input[type='text']"),function(index,obj){
                if($(obj).val()==null||$(obj).val()==""){
                    obj.focus();
                    result = false;
                    return false;
                }
            });
            if(result == false) return false;
           var datepicker_start = $("#datepicker_start").val();
           var datepicker_end = $("#datepicker_end").val();

           var datepicker_start_ext1 = $("#datepicker_start_ext1").val();
           var datepicker_end_ext1 = $("#datepicker_end_ext1").val();

           var datepicker_start_ext2 = $("#datepicker_start_ext2").val();
           var datepicker_end_ext2 = $("#datepicker_end_ext2").val();

            if(datepicker_start > datepicker_end || datepicker_start_ext1 > datepicker_end_ext1 || datepicker_start_ext2>datepicker_end_ext2){
                alert("学习开始日期不能早于结束日期!");
                return false;
            }

            if(datepicker_start > datepicker_start_ext1 || datepicker_start > datepicker_start_ext2){
                alert("3+3+1学习的开始日期不能早于6+1学习的开始日期!");
                return false;
            }

            if(datepicker_end < datepicker_end_ext1 || datepicker_end < datepicker_end_ext2){
                alert("3+3+1学习的截止日期不能晚于6+1学习的截止日期！");
                return false;
            }

            var datetimepicker1 = $("#datetimepicker1").val();
            var datetimepicker2 = $("#datetimepicker2").val();
            var datetimepicker3 = $("#datetimepicker3").val();
            var datetimepicker4 = $("#datetimepicker4").val();

            if(datetimepicker1 < '08:00'){
                alert("上午开始学习时间不正确，请重新设置！");
                return false;
            }
            if(datetimepicker2 > '12:00'){
                alert("上午结束学习时间不正确，请重新设置！");
                return false;
            }
            if(datetimepicker3 < "12:00") {
                alert("下午开始学习时间不正确，请重新设置！");
                return false;
            }
            if(datetimepicker1 > datetimepicker2){
                alert("上午学习时间不正确，请重新设置！");
                return false;
            }
            if(datetimepicker4 < datetimepicker3){
                alert("下午学习时间不正确，请重新设置！");
                return false;
            }
            var xxsj = "上午" + datetimepicker1 + "至" + datetimepicker2+",下午" + datetimepicker3 + "至" + datetimepicker4;

            vm.subscribedate.startdate =  datepicker_start;
            vm.subscribedate.enddate = datepicker_end;
            vm.subscribedate.xxsj = xxsj;
            vm.subscribedate.studytype = "1";
            vm.subscribedate.subscribedate = datepicker_start+"至"+datepicker_end;

            vm.ext1.startdate = datepicker_start_ext1;
            vm.ext1.enddate = datepicker_end_ext1;
            vm.ext1.xxsj = xxsj;
            vm.ext1.xxdd = vm.subscribedate.xxdd;
            vm.ext1.studytype = "2";
            vm.ext1.subscribedate =datepicker_start_ext1+"至"+datepicker_end_ext1;

            vm.ext2.startdate = datepicker_start_ext2;
            vm.ext2.enddate = datepicker_end_ext2;
            vm.ext2.xxsj = xxsj;
            vm.ext2.xxdd = vm.subscribedate.xxdd;
            vm.ext2.studytype = "2";
            vm.ext2.subscribedate = datepicker_start_ext2+"至"+ datepicker_end_ext2;
           return true;
        }
	}
});
